﻿using MPXJ.Net;

namespace apitest.Application.Test.Services
{
    public class MppService : IDynamicApiController
    {
        public async Task<dynamic> T1()
        {
            UniversalProjectReader reader = new UniversalProjectReader();
            ProjectFile project = reader.Read("./123.mpp");
            var aa = project.JavaObject.getCustomFields();
            var bb = project.Tasks[15].JavaObject.getFieldByAlias("责任部门");
            var name = project.Tasks[15].Name;
            var cc = project.Tasks[15];
            var a = 1;
            return project.Tasks.Select(o => new
            {
                o.ID,
                o.Name,
                RemainingDuration = o.RemainingDuration.DurationValue.ToString() + Enum.GetName(typeof(TimeUnit), o.RemainingDuration.Units.Value),
                o.UniqueID,
                ChildTasksCount = o.ChildTasks.Count,
            }).ToList();
        }

        public async Task<dynamic> T2()
        {
            UniversalProjectReader reader = new UniversalProjectReader();
            ProjectFile project = reader.Read("./123.mpp");
            //var res = new List<TaskResultClass>();
            var list = new List<TaskResultClass>();
            GetTask(project.Tasks.ToList(), list);
            
            return list.OrderBy(o=>o.Id).Distinct().ToList();
        }

        void GetTask(List<MPXJ.Net.Task> tasks, List<TaskResultClass> list)
        {
            foreach (var task in tasks)
            {
                if (!list.Any(o => o.Id == task.ID))
                {
                    list.Add(new TaskResultClass
                    {
                        Name = task.Name,
                        Department = task.JavaObject.getFieldByAlias("责任部门") + "",
                        EarlyStart = task.EarlyStart,
                        EarlyFinish = task.EarlyFinish,
                        Id = task.ID.Value,
                        Duration = task.RemainingDuration.DurationValue + "" + Enum.GetName(typeof(TimeUnit),
                        task.RemainingDuration.Units.Value),
                        ParentId = task.ParentTask?.ID,
                        ChildrenTaskCount=task.ChildTasks.Count
                    });
                }
                if (task.HasChildTasks)
                {
                        GetTask(task.ChildTasks.ToList(), list);
                }
                
              
            }
           
        }

        public class TaskResultClass
        {
            public int Id { get; set; }
            public int? ParentId { get; set; }
            public string Name { get; set; }
            public string Duration { get; set; }
            public string Department { get; set; }
            public DateTime? EarlyStart { get; set; }
            public DateTime? EarlyFinish { get; set; }
            public int ChildrenTaskCount { get; set; }
        }
    }
}
